/* 
 * Copyright (C) 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package bhoost.shell;

import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.hardware.CameraDevice;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.Toast;

public class CameraPreview extends Activity {    
    private Preview mPreview;
    private String TAG = "CAMERA_PREVIEW";
    private boolean shotTaken = false;
    private String writepath;
    private String toastResume = "Click DPad center to shoot, or Back to exit";
    private String toastPause = "Click DPad center to use this photo, or Back to reshoot";
    private int width;
    private int height;
    
    @Override
	protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        writepath = getIntent().getStringExtra("writepath");
                
        // Hide the window title.
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    
        // Create our Preview view and set it as the content of our
        // Activity
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        width = dm.widthPixels;
        height = dm.heightPixels;

        mPreview = new Preview(this, width, height);
        setContentView(mPreview);
        Toast.makeText(this, toastResume, Toast.LENGTH_SHORT).show();
  }

  @Override
	protected void onResume() {
        // Because the CameraDevice object is not a shared resource,
        // it's very important to release it when the activity is paused.
        super.onResume();
        mPreview.resume();
        shotTaken = false;
  }

    @Override
	protected void onPause() {
        // Start Preview again when we resume.
        super.onPause();
        mPreview.pause();
        shotTaken = true;
  }
    
  @Override
  public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
      case KeyEvent.KEYCODE_DPAD_CENTER:
        if (shotTaken) {
          setResult(RESULT_OK);
          finish();
          return true;
        }
        Log.d(TAG, "pausing");
        Toast.makeText(this, toastPause, Toast.LENGTH_SHORT).show();
        mPreview.pause();
        Log.d(TAG, "taking picture");
        shotTaken = true;
        takePicture();
        return true;
      case KeyEvent.KEYCODE_BACK:
        if (!shotTaken) {
          setResult(RESULT_CANCELED);
          finish();
          return true;
        }
        Log.d(TAG, "resuming");
        Toast.makeText(this, toastResume, Toast.LENGTH_SHORT).show();
        mPreview.resume();
        shotTaken = false;
        return true;
    }
    
    return super.onKeyDown(keyCode, event);
  }
  
  @Override
  public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "destroy!!");
  }
  
  public void takePicture(){
    CameraDevice camera = CameraDevice.open();
    if (camera != null) {
         Log.d(TAG, "inside the camera");
         CameraDevice.CaptureParams param = new CameraDevice.CaptureParams();
         param.type = 1; // preview
         param.srcWidth = 1280;
         param.srcHeight = 960;
         param.leftPixel = 0;
         param.topPixel = 0;
         param.outputWidth = width;
         param.outputHeight = height;
         param.dataFormat = 2; // RGB_565
         camera.setCaptureParams(param);
         
         Bitmap myPic = Bitmap.createBitmap(width, height, false);
         Canvas canvas = new Canvas(myPic);
         try {
            File file = new File(writepath);
            FileOutputStream stream = new FileOutputStream(file); //super.openFileOutput(writepath, MODE_PRIVATE);
            camera.capture(canvas);
            if (writepath.toLowerCase().contains(".jp"))
              myPic.compress(Bitmap.CompressFormat.JPEG, 50, stream); // 50 out of 100 quality
            else if (writepath.toLowerCase().contains(".png"))
              myPic.compress(Bitmap.CompressFormat.PNG, 50, stream); // 50 out of 100 quality
            stream.flush();
            stream.close();
         } catch(Exception e) { Log.d(TAG, e.toString()); }
         
         // Make sure to release the CameraDevice
         if (camera != null)
              camera.close();
    }
  } 
}

// ----------------------------------------------------------------------
